/*******************************************************************************
 * Owlets Framework
 * Copyright 2011 Logicfish Software http://logicfishsoftware.com/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 * 
 * @author logicfish@gmail.com
 *
 ******************************************************************************/

package com.logicfishsoftware.owlet.app.runtime;

import com.logicfishsoftware.owlet.app.ApplicationException;


/**
 * @author logicfish@gmail.com
 *
 */
public abstract class TransactionalRuntime<T extends RuntimeApplication<T,U>.ApplicationAtom,
		U extends TransactionalRuntime<T,U>.TransactionalContext> 
extends RuntimeApplication<T,U> {
	
	public abstract class TransactionalContext extends RuntimeApplication<T,U>.ApplicationContext {

		protected abstract void commit(T atom) throws ApplicationException;

		protected abstract void rollback(T atom) throws ApplicationException;
		
		/* (non-Javadoc)
		 * @see com.logicfishsoftware.owlet.app.app.ApplicationRuntime.ApplicationFrame#dispose()
		 */
		protected abstract void dispose() throws ApplicationException;

	}
	
	@Override
	protected boolean apply(U context,T atom) throws ApplicationException {
		boolean proceed = false;
		try {
			if(proceed = atom.application(context)) 
				context.commit(atom);
			else context.rollback(atom);
		} catch (Throwable throwable) {
			context.rollback(atom);
			throw new ApplicationException(throwable);
		} finally {
			context.dispose();
		}
		context = null;
		if(proceed) {
			T tail = atom.proceed();
			atom = null;
			if(tail!=null) 
				enter(tail);
		}
		return proceed;
	}


}
